#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TCP client for the dictionary service (UTF-8).
Usage:
  python client.py <server_host> <port>
Example:
  python client.py 127.0.0.1 5555
Then type lines like:
  en:apple
  zh:苹果
  hello
Press Ctrl-D (Linux/macOS) or Ctrl-Z Enter (Windows) to exit.
"""
import sys
import socket

def recv_line(sock: socket.socket) -> str | None:
    buf = bytearray()
    while True:
        chunk = sock.recv(1024)
        if not chunk:
            return None if not buf else buf.decode("utf-8", errors="replace")
        buf.extend(chunk)
        if b"\n" in chunk:
            break
    # split at first newline
    raw = bytes(buf)
    if b"\n" in raw:
        line, rest = raw.split(b"\n", 1)
    else:
        line, rest = raw, b""
    # Put back 'rest' into an internal buffer is complex with raw sockets;
    # for our simple request/response protocol, we expect exactly one line back.
    return line.decode("utf-8", errors="replace")

def main():
    if len(sys.argv) < 3:
        print(f"Usage: {sys.argv[0]} <server_host> <port>")
        sys.exit(1)
    host, port = sys.argv[1], int(sys.argv[2])

    # Create TCP socket
    with socket.create_connection((host, port)) as sock:
        print("Connected. Enter queries like 'en:apple' or 'zh:苹果'. Ctrl-D to quit.")
        while True:
            try:
                line = input("> ")
            except EOFError:
                print()
                break
            # Ensure newline-terminated UTF-8
            data = (line + "\n").encode("utf-8")
            try:
                sock.sendall(data)
            except OSError as e:
                print("send failed:", e)
                break

            resp = recv_line(sock)
            if resp is None:
                print("server closed connection")
                break
            print(resp)

if __name__ == "__main__":
    main()
